package com.xjoyt.pay.share.api.ali.area;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.xjoyt.pay.share.api.ali.area.dto.ApiAreaItem;
import com.xjoyt.pay.share.api.ali.area.dto.ApiResult;

@Component
public class AreaClient {

	private String API_URL = "http://ali-city.showapi.com/areaDetail?parentId=%s";

	@Autowired
	private RestTemplate restTemplate;

	public List<ApiAreaItem> getAreaIems(String key, String parentId) {
		MultiValueMap<String, String> headers = new HttpHeaders();
		headers.add("Authorization", "APPCODE " + key);
		HttpEntity<String> httpEntity = new HttpEntity<>(null, headers);
		String url = String.format(API_URL, parentId);
		ResponseEntity<ApiResult> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, ApiResult.class);
		if (response.getStatusCodeValue() != 200 || response.getBody() == null || response.getBody().code != 0
				|| response.getBody().body == null || CollectionUtils.isEmpty(response.getBody().body.data)) {
			return null;
		}

		return response.getBody().body.data;
	}
}
